#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <zlib/net/I_UnixNet.h>
#include <sys/eventfd.h>
#include <string.h>

using namespace std;

int evfd;

void *test(void *arg)
{
	cout << EVENTIO_READ << " " << EVENTIO_WRITE << endl;
	(void)arg;

	PollPoller poller;
	EventIO eventIO;
	evfd = ::eventfd(0, 0);
	fcntl(evfd, F_SETFD, FD_CLOEXEC);
	fcntl(evfd, F_SETFL, O_NONBLOCK);

	eventIO.start(poller.pd, evfd, NULL, EVENTIO_READ | EVENTIO_WRITE);
	char buff[1024];
	char writebuff[1024];
	uint64_t a = 1;
	int xxx = 0;
	while(1)
	{
		int res = write(evfd, &a, sizeof(a));
		poller.pollEvent(5000);

		if(poller.pd->result > 0)
		{
			//the testing has bug.....
			//if the events has READ and WRITE events, the READ events call add WRITE events, but the WRITE events remove WRITE events.
			//so the WRITE events amount is xxx/2
			for(int i = 0; i < poller.pd->result; i++)
			{
				if(poller.pd->get_ev_events(i) & EVENTIO_READ)
				{
					//cout << "read events" << endl;
					EventIO *ep = (EventIO *)poller.pd->get_ev_data(i);
					int len = read(ep->fd, buff, sizeof(buff));

					if(len > 0){
						if(xxx > 20)
							continue;
						xxx++;
						//listen write events
						ep->modify(EVENTIO_WRITE, true);
					}else{
						cout << len << endl;
					}
				}

				if(poller.pd->get_ev_events(i) & EVENTIO_WRITE)
				{
					cout << "write events" << endl;
					EventIO *ep = (EventIO *)poller.pd->get_ev_data(i);
					ep->modify(EVENTIO_WRITE, false);
				}
			}
		}	
	}

	return NULL;
}

//simple testing
int main()
{
	//PollPoller poller;
	pthread_t pid;
	pthread_create(&pid, NULL, test, NULL);

	while(1)
	{
		sleep(1);
	}

	return 0;	
}
